import type { FC } from 'react';
import { Spin } from 'antd';
import { useContext } from 'react';
import { useAsyncEffect, useMemoizedFn, useSafeState } from 'ahooks';
import type { ToolsProps, ToolItem } from './types';
import ToolButton from '../ToolButton';
import Context from './context';
import styles from './styles.module.less';

const Tools: FC<ToolsProps> = (props) => {
  const { tab, tools, activeId } = props;
  const [items, setItems] = useSafeState<ToolItem[]>([]);
  const { onToolClick, onLoadedIcons } = useContext(Context);

  const loadTools = useMemoizedFn(async () => {
    let items: ToolItem[] = [];
    if (Array.isArray(tools)) {
      items = tools;
    } else {
      items = await tools();
    }
    setItems(items);
    onLoadedIcons?.(tab, items);
  });

  useAsyncEffect(loadTools, [tab, tools]);

  return (
    <Spin spinning={!items.length}>
      <div className={styles.tools}>
        {items.map(item => {
          return (
            <div
              key={item.id}
              className={styles.tool_item}
            >
              <ToolButton
                title={item.title}
                selected={item.id === activeId}
                svgComponent={item.svgComponent}
                onClick={() => onToolClick?.(tab, item)}
              />
            </div>
          );
        })}
      </div>
    </Spin>
  );
}

export default Tools;